package biznussoft.metercor.fragments;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import biznussoft.metercor.HomeActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.adapter.ActivitesAdapter;
import biznussoft.metercor.listeners.ActivityDetailListener;
import biznussoft.metercor.listeners.DialogListener;
import biznussoft.metercor.listeners.GlobalListener;
import biznussoft.metercor.lookup.AccountLookup;
import biznussoft.metercor.lookup.ContactsLookUp;
import biznussoft.metercor.lookup.InstalledProductLookUp;
import biznussoft.metercor.lookup.SiteLookUp;
import biznussoft.metercor.lookup.TechnicianLookUp;
import biznussoft.metercor.model.ActivityModel;
import biznussoft.metercor.model.Bean_Class;
import biznussoft.metercor.model.ServiceOrderModel;
import biznussoft.metercor.model.SiteInventoryModel;
import biznussoft.metercor.utils.Base64;
import biznussoft.metercor.utils.Session;

import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ServiceOrderDetailsFragment extends BaseFragment implements OnItemClickListener, OnClickListener {
	private LocationListener mLocationListener;

	private DialogListener dialoglistener;
	private String mFileName,mImagePath,serviceOrder;
	private static final int RESULT_CAMERA = 2;
	private LocationClient locationClient;
	TextView header1,header2;
	ImageView imageview1,imageview2;
	private String destinatioAddress,strImage,strSignature;
	LinearLayout llayoutServiceOrderDetails,serviceOrderDetailsEdit;
	private Double lat,lon;
	private TextView editServiceId,editBiliadress,tvInstalledProducts,tvProductId,tvAgreementName,tvEntitledGroupName,tvServiceName,tvServicedescription,tvServiceOrderId,tvAccount,tvBillAdress,tvContact,tvSiteName,tvAdress,tvBillable,tvNoOfActivites,
	tvPhone,tvPriority,tvStatus,tvStartDate;
	private EditText etEntitledGroupName,etServiceName,tvBillAdress1;
	public static EditText etAccount,etInstalledProducts,etTechnician,etContact,etSiteName;
	private ListView lv,inventoryListView;
	private ImageView signatureCapture,imageCapture,sign,image;
	Button submit;
	static ArrayList<ActivityModel> list ;
	private ActivityDetailListener listener1;
	private RestClient client;
	private GlobalListener listener;
	private ServiceOrderModel mobel;
	static ArrayList<SiteInventoryModel> inventoryList;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.serviceorder_details_fragment, null);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);               
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {



		MenuItem addAccount = menu.add("GetDirection");
		MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addAccount.setIcon(R.drawable.direction); 
		MenuItem edit = menu.add("Edit");
		MenuItemCompat.setShowAsAction(edit, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		edit.setIcon(R.drawable.edit); 
		/*MenuItem addwater = menu.add("Water Meter Data Management");                 
		MenuItemCompat.setShowAsAction(addwater,MenuItemCompat.SHOW_AS_ACTION_NEVER | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addwater.setIcon(R.drawable.add);
		MenuItem addGas = menu.add("Gas Meter Management");                 
		MenuItemCompat.setShowAsAction(addGas,MenuItemCompat.SHOW_AS_ACTION_NEVER | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addGas.setIcon(R.drawable.add);*/

		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 
		super.onCreateOptionsMenu(menu, inflater);
	}                         


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		if(item.getTitle().equals("GetDirection")){
			new MyAsynTask().execute();
		}
		if(item.getTitle().equals("Edit")){
			llayoutServiceOrderDetails.setVisibility(View.GONE);
			serviceOrderDetailsEdit.setVisibility(View.VISIBLE);

			
			etServiceName = (EditText) getView().findViewById(R.id.etServiceName);
			etAccount = (EditText) getView().findViewById(R.id.etSAccount);
			etContact =  (EditText) getView().findViewById(R.id.etContact);
			etSiteName = (EditText) getView().findViewById(R.id.etSiteName);

			editBiliadress.setText(mobel.getBillToAddress());
			editServiceId.setText(mobel.getName());
			etSiteName.setText(mobel.getSiteName());
			etAccount.setText(mobel.getAccountName());
			etContact.setText(mobel.getContactName());
			etInstalledProducts.setText(mobel.getProductName());
			etTechnician.setText(Session.sFirstName+" "+Session.sLastName);
			etEntitledGroupName.setText(mobel.getEntitleGroupName());
			etServiceName.setText(mobel.getServiceName());
		}

		/*if(item.getTitle().equals("Water Meter Data Management")){
			listener1.getCategory("Water", "");
		}
		if(item.getTitle().equals("Gas Meter Management")){
			listener1.getCategory("Gas", "");
		}*/


		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onAttach(Activity activity) {          
		// TODO Auto-generated method stub
		super.onAttach(activity);
		listener = (GlobalListener) getActivity();
		dialoglistener = (DialogListener) getActivity();
		listener1 = (ActivityDetailListener) getActivity();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.siteListview);
		lv.setOnItemClickListener(this);
		client =  HomeActivity.mActivity.client;
		 header1 = (TextView) getView().findViewById(R.id.tvHeader1);
		header1.setText("Water Meter Data Management");
		imageview1 = (ImageView) getView().findViewById(R.id.iv_CollapseExpand1);
		imageview1.setOnClickListener(this);
		header2 = (TextView) getView().findViewById(R.id.tvHeader2);
		header2.setText("Gas Meter Management");
		imageview2 = (ImageView) getView().findViewById(R.id.iv_CollapseExpand2);
		imageview2.setOnClickListener(this);
		
		serviceOrderDetailsEdit  = (LinearLayout) getView().findViewById(R.id.serviceOrderDetails);
		llayoutServiceOrderDetails  = (LinearLayout) getView().findViewById(R.id.llayoutServiceOrderDetails);

		editServiceId = (TextView) getView().findViewById(R.id.tvorderidabc);
		editBiliadress = (TextView) getView().findViewById(R.id.tvBilltoaddressabc); 
		tvServiceOrderId = (TextView) getView().findViewById(R.id.tvorderid123);
		tvSiteName = (TextView) getView().findViewById(R.id.tvSiteName);
		tvAccount = (TextView) getView().findViewById(R.id.tvAccount);
		tvBillAdress = (TextView) getView().findViewById(R.id.tvBilltoaddress123);
		tvContact = (TextView) getView().findViewById(R.id.tvContact);
		tvAdress = (TextView) getView().findViewById(R.id.tvAddress);
		tvInstalledProducts = (TextView) getView().findViewById(R.id.tvInstalledProducts);
		tvAgreementName = (TextView) getView().findViewById(R.id.tvAgreement);
		tvEntitledGroupName = (TextView) getView().findViewById(R.id.tvEntitledGroup);
		tvServiceName = (TextView) getView().findViewById(R.id.tvServiceName);
		tvServicedescription = (TextView) getView().findViewById(R.id.tvServiceDescription);
		tvProductId = (TextView) getView().findViewById(R.id.tvProductId123);
		tvBillable = (TextView) getView().findViewById(R.id.tvBillable);
		tvNoOfActivites = (TextView) getView().findViewById(R.id.tvNo_ofactivites);
		tvPhone = (TextView) getView().findViewById(R.id.tvPhone);
		tvPriority = (TextView) getView().findViewById(R.id.tvPriority);
		tvStatus = (TextView) getView().findViewById(R.id.tvStatus);
		tvStartDate = (TextView) getView().findViewById(R.id.tvStatDate);


		etInstalledProducts = (EditText) getView().findViewById(R.id.etInstallationProducts);
		etInstalledProducts.setOnClickListener(this);
		etTechnician = (EditText) getView().findViewById(R.id.etTechnician);
		etTechnician.setOnClickListener(this);
		etEntitledGroupName = (EditText) getView().findViewById(R.id.etEntitledGroup);
		etServiceName = (EditText) getView().findViewById(R.id.etServiceName);
		etAccount = (EditText) getView().findViewById(R.id.etSAccount);
		etContact =  (EditText) getView().findViewById(R.id.etContact);
		etSiteName = (EditText) getView().findViewById(R.id.etSiteName);

		etSiteName.setOnClickListener(this);
		etAccount.setOnClickListener(this);
		etContact.setOnClickListener(this);
		submit = (Button) getView().findViewById(R.id.serviceOrderEditsubmit);
		submit.setOnClickListener(this);
		signatureCapture = (ImageView) getView().findViewById(R.id.signImage2);
		signatureCapture.setOnClickListener(this);
		sign = (ImageView) getView().findViewById(R.id.signature2);
		imageCapture = (ImageView) getView().findViewById(R.id.captureImage2);
		imageCapture.setOnClickListener(this);
		image = (ImageView) getView().findViewById(R.id.picture2);

		mFileName = "image"+".jpg";
		mImagePath = Environment.getExternalStoragePublicDirectory("download")+"/canvas/";


	}


	public void getWarehouseDetails(int Position,String category){      


		if(category.equalsIgnoreCase("ServiceOrder")){
			mobel = ServiceOrderFragment.serviceOrderList.get(Position);
			list = ServiceOrderFragment.activityDetailsList.get(mobel.getId());
			ActivitesAdapter adapter = new ActivitesAdapter(getActivity(),list);
			lv.setAdapter(adapter);
		}else{

			mobel = AccountsFragment.serviceList.get(Position);
		}

		Session.sServiceOrderId = mobel.getId();
		Log.i("RGT","Session.sServiceOrderId   :"+Session.sServiceOrderId);
		tvServiceOrderId.setText(mobel.getName());
		tvSiteName.setText(mobel.getSiteName());
		tvAccount.setText(mobel.getAccountName());
		tvBillAdress.setText(mobel.getBillToAddress());                   
		tvContact.setText(mobel.getContactName());
		destinatioAddress = mobel.getAddress();
		tvAdress.setText(destinatioAddress);
		tvBillable.setText(mobel.getBillable());
		tvNoOfActivites.setText(mobel.getActivities());
		tvPhone.setText(mobel.getAlternatePhone());
		tvPriority.setText(mobel.getPriority());
		tvStatus.setText(mobel.getStatus());
		tvStartDate.setText(mobel.getStartDate());
		
		tvInstalledProducts.setText(mobel.getProductName());
		tvProductId.setText(mobel.getTechnician());
		tvAgreementName.setText(mobel.getAgreementName());
		tvEntitledGroupName.setText(mobel.getEntitleGroupName());
		tvServiceName.setText(mobel.getServiceName());
		tvServicedescription.setText(mobel.getServiceDescription());



	}



	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

		switch (arg0.getId()) {
		case R.id.siteListview:
			ActivityModel bean = list.get(position);
			Session.sActivityId = bean.getActivityName();
			listener.onGetContacts(position, mobel.getName());
			break;
		default:
			break;
		}


	}



	/*@Override
	public void onClick(View arg0) {
		 MyLocationManager loc = new MyLocationManager(getActivity());
		 loc.getLocations();
	}*/

	/* class MyLocationManager implements OnConnectionFailedListener ,ConnectionCallbacks{
	    	public Location location;
	    	private Context mContext;

	    	public MyLocationManager(Context context) {

	    		mContext = context;
	    	}

	    	public void getLocations() {
	    				 locationClient = new LocationClient(mContext, this, this);
	    				 locationClient.connect();
	    			}

	    	public void onConnected(Bundle connectionHint) {

	    			LocationRequest lRequest = LocationRequest.create().setInterval(1000).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	    			 mLocationListener = new LocationListener() {

	    				public void onLocationChanged(Location location) {
	    					lat = location.getLatitude();
	    					lon = location.getLongitude();
	    					//new MyAsynTask().execute();
	    				}
	    			};

	    			locationClient.requestLocationUpdates(lRequest, mLocationListener);


	    	}

	    	public void onDisconnected() {

	    	}

	    	public void onConnectionFailed(ConnectionResult result) {

	    	}
	    }*/


	public class MyAsynTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			try {
				Log.i("NCS","lat :  "+Session.sLatitude +" :  "+Session.sLongitude);
				getLocationInfo(Session.sLatitude,Session.sLongitude);
			} catch (Exception e) {
				Log.i("NCS","Exception :  "+e.getMessage());
			}
			return null;
		}

	}


	public  void getLocationInfo(Double lat,Double lon) {

		HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=false");
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		StringBuilder stringBuilder = new StringBuilder();

		try {
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				stringBuilder.append((char) b);
			}
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}

		JSONObject jsonObject = new JSONObject();

		try {
			jsonObject = new JSONObject(stringBuilder.toString());
			getGeoPoint(jsonObject);
		} catch (JSONException e) {
			Log.i("NCS", "Exception 1 is  :  " + e.getMessage());
		}


	}


	public  void getGeoPoint(JSONObject jsonObject) {


		try {
			locationClient.removeLocationUpdates(mLocationListener);
			JSONArray results = jsonObject.getJSONArray("results");
			JSONObject js = results.getJSONObject(0);
			String adress = js.getString("formatted_address");

			/*String uri = "http://maps.google.com/maps?saddr="+adress+"&daddr="+"Begumpet, Hyderabad, Andhra Pradesh";
				 Intent i = new  Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+"Begumpet, Hyderabad, Andhra Pradesh"));       
				Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
				intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
				startActivity(i); */
			String uri = "http://maps.google.com/maps?saddr="+adress+"&daddr="+"Begumpet, Hyderabad, Andhra Pradesh";
			Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
			intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
			startActivity(intent);    
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}

	public void getSignature(String signature){
		try{
			strSignature = signature;
			byte[] decodedString = Base64.decode(signature);
			Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
			sign.setImageBitmap(decodedByte);
		}catch (Exception e) {
		}

	}           
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_CollapseExpand1:
			listener.onCategoryClicked(1);
			break;
		case R.id.iv_CollapseExpand2:
			listener.onCategoryClicked(2);
			break;

		case R.id.serviceOrderEditsubmit:
			updateServiceOrder(mobel.getId());
			break;
		case R.id.etSiteName:
			SiteLookUp siteLookup = new SiteLookUp();
			siteLookup.accountLookupDetails(getActivity(),"site");
			break;
		case R.id.etContact:
			ContactsLookUp contactlookup = new ContactsLookUp();
			contactlookup.accountLookupDetails(getActivity(),"contact");
			break;
		case R.id.etSAccount:
			AccountLookup acountLookup = new AccountLookup();
			//			acountLookup.accountLookupDetails(getActivity(),"Account",client);
			break;
		case R.id.signImage2:                
			dialoglistener.nextDialog("sign2");
			break;
		case R.id.captureImage2:
			File file = checkFileExistence(mImagePath, mFileName);
			init_Camera(file);
			break;
		case R.id.etInstallationProducts:
			InstalledProductLookUp lookup = new InstalledProductLookUp();
			lookup.getItemLookUp(getActivity(),"Installed");
			break;
		case R.id.etTechnician:
			TechnicianLookUp lookup2 = new TechnicianLookUp();
			lookup2.getItemLookUp(getActivity(),"Technician");
			break;
		default:
			break;
		}

	}


	private void updateServiceOrder(String id){


		String objectType = "FConnect__service_order__c";                                 
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("FConnect__Account__c",Session.sAccountId);
		fields.put("FConnect__Contact__c",Session.sContactId);
		fields.put("FConnect__Site_Name__c",Session.sSiteId);
		fields.put("FConnect__Installed_Product__c",Session.sInstalledProductId);
		fields.put("Technician__c",Session.sTechnicianId);
		fields.put("sign__c","<img src="+"\"data:image/png;base64,"+strSignature+"\"/>");                                                                                                                                            
		fields.put("Picture__c","<img src="+"\"data:image/png;base64,"+strImage+"\"/>" );  

		Log.i("NCS","Request 1 is   :"+fields);

		try {

			RestRequest restRequest = RestRequest.getRequestForUpdate(Bean_Class.api_Version,objectType,id,fields);
			Log.i("NCS","Request 2 is   :"+restRequest);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {     
						Log.i("NCS","RestResponse is   :"+result); 
						finishFragment();
					}                                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}

				//@Override
				public void onError(Exception exception) {

					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}

	}

	public static File checkFileExistence(String path, String fileName) {
		if (!new File(path).exists()) {
			new File(path).mkdirs();
		}
		File file = new File(path, fileName);
		return file;
	}                

	public void init_Camera(File file) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(intent,RESULT_CAMERA);
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			try {
				UpdateUIWithImages(mFileName);
			} catch (Exception e) {
				Log.i("Today","Display Image"+e.getMessage());
			}
		}
	}

	private void UpdateUIWithImages(String fileName) throws Exception {

		File file = new File(mImagePath+"/"+fileName);
		Bitmap bitmap  = getFileFromStorage(file);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
		byte[] imagebyte = stream.toByteArray();             
		/*String img_str = Base64.encodeToString(imagebyte, Base64.DEFAULT);     
    	byte[] decodedString = Base64.decode(img_str, Base64.DEFAULT);
    	Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
    	image.setImageBitmap(decodedByte);  */        
		strImage = Base64.encodeBytes(imagebyte);     
		byte[] decodedString = Base64.decode(strImage);
		Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
		image.setImageBitmap(decodedByte);  
	}

	private Bitmap getFileFromStorage(File file) throws Exception {
		try {
			// decode image size
			Bitmap retBmp = null;
			System.gc();
			int scale = 1;
			if (file.length() > 400000) {
				scale = 4;
			} else if (file.length() > 100000 && file.length() < 400000) {
				scale = 2;
			}
			// decode with inSampleSize
			if (file.exists()) {
				BitmapFactory.Options bitmapFactoryObject = new BitmapFactory.Options();
				bitmapFactoryObject.inSampleSize = scale;
				retBmp = BitmapFactory.decodeFile(file.getPath(), bitmapFactoryObject);
			}

			return rotateImage(retBmp, file.getPath());
		} catch (Exception t) {
			t.printStackTrace();
			// CustomLogHandler.printErrorlog(t);
			throw new Exception(
					"Today"
							+ " Error in getFileFromStorage(File p_file) of ImageLoader",
							t);
		}
	}
	private Bitmap rotateImage(Bitmap decodedbitMap, String path) throws Exception {
		try {
			ExifInterface exif = new ExifInterface(path);
			String orientString = exif
					.getAttribute(ExifInterface.TAG_ORIENTATION);
			int orientation = orientString != null ? Integer
					.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
					int rotationAngle = 0;
					if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
						rotationAngle = 90;
					if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
						rotationAngle = 180;
					if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
						rotationAngle = 270;

					Matrix matrix = new Matrix();
					matrix.setRotate(rotationAngle);
					Bitmap rotatedBitmap = Bitmap.createBitmap(decodedbitMap, 0, 0,
							decodedbitMap.getWidth(), decodedbitMap.getHeight(), matrix, true);
					//
					FileOutputStream fileOutputStream = new FileOutputStream(path);
					rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50,
							fileOutputStream);

					return rotatedBitmap;

		}

		catch (Throwable t) {
			// CustomLogHandler.printErrorlog(t);
			throw new Exception("Today" + " Error in rotateImage:", t);
		}

	}
	public void finishFragment(){
		getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
	}



}
